/*
 Basic ESP8266 MQTT example
 This sketch demonstrates the capabilities of the pubsub library in combination
 with the ESP8266 board/library.
 It connects to an MQTT server then:
  - publishes "hello world" to the topic "outTopic" every two seconds
  - subscribes to the topic "inTopic", printing out any messages
    it receives. NB - it assumes the received payloads are strings not binary
  - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
    else switch it off
 It will reconnect to the server if the connection is lost using a blocking
 reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
 achieve the same result without blocking the main loop.
 To install the ESP8266 board, (using Arduino 1.6.4+):
  - Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
       http://arduino.esp8266.com/stable/package_esp8266com_index.json
  - Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
  - Select your ESP8266 in "Tools -> Board"
*/

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <PubSubClient.h>
#include <IRsend.h>

#define CLIENT_ID "hw/home"

char ircmd1[] = "hw/ir/1";
char ircmd2[] = "hw/ir/2";
char wolcmd[] = "hw/home/wol";


// Update these with values suitable for your network.
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 177);
IPAddress dns(192, 168, 1, 1);

const char* mqtt_server = "119.91.90.201";
unsigned int mqtt_port = 1883;
String clientId = CLIENT_ID; //"ESP8266Client-home";

EthernetClient ethclient;
EthernetUDP Udp;
PubSubClient client(ethclient);
IRsend irsend1(D2);
IRsend irsend2(D3);

#define BUFFER_SIZE 1001

//唤醒主机
void wakeupPC(byte destMac[])
{
    byte all[102];
    int i,c1,j=0;

    IPAddress remoteIp(255,255,255,255);
    
  digitalWrite(LED_BUILTIN, LOW);
  Serial.println("Sending WOL Packet...");
  for(i=0; i<6; i++)
    Serial.print(destMac[i], HEX);
  Serial.println();

  for(i = 0; i < 6; i++,j++){
    all[j] = 0xFF;
  }
  for(i = 0; i < 16; i++){
    for( c1 = 0; c1 < 6; c1++,j++)
      all[j] = destMac[c1];
  }

  Udp.begin(8888);
  Udp.beginPacket(remoteIp, 9);
  Udp.write(all, 102);
  Udp.endPacket();

  digitalWrite(LED_BUILTIN, HIGH);
}

void IRcontrol(IRsend *pirsend, uint16_t rawData[], int dataLength)
{
  
  digitalWrite(LED_BUILTIN, LOW);
  for (int i = 0; i < dataLength; i++) {
    Serial.print(rawData[i]);
    Serial.print(',');
    if (i%8 == 7) Serial.println();
  }
  Serial.println();
  pirsend->sendRaw(rawData, dataLength, 38);
  delay(200);
  pirsend->sendRaw(rawData, dataLength, 38);
  digitalWrite(LED_BUILTIN, HIGH);

}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] length: ");
  Serial.println(length);

  if (length >= BUFFER_SIZE)
  {
    Serial.println("Payload Too Large!!!");
    return;
  }

  if (strcmp(topic, ircmd1) == 0)
  {
    IRcontrol(&irsend1, (uint16_t *)payload, length/sizeof(uint16_t));
  } 
  if (strcmp(topic, ircmd2) == 0)
  {
    IRcontrol(&irsend2, (uint16_t *)payload, length/sizeof(uint16_t));
  } 
  else if (strcmp(topic, wolcmd) == 0)
  {
    wakeupPC(payload);
  }
  delay(2000);

  // Switch on the LED if an 1 was received as first character
//  if ((char)payload[0] == '1') {
//    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
//    // but actually the LED is on; this is because
//    // it is active low on the ESP-01)
//  } else {
//    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
//  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      //client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("hw/ir/+");
      client.subscribe(wolcmd);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(9600);
  Serial.println("Hello");
  
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  digitalWrite(LED_BUILTIN, HIGH);

  Ethernet.init(5);
  // start the Ethernet connection and the server:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1); // do nothing, no point running without Ethernet hardware
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // try to congifure using IP address instead of DHCP:
    Ethernet.begin(mac, ip, dns);
  } else {
    Serial.print("  DHCP assigned IP ");
  }
//  Ethernet.begin(mac, ip, dns);
  Serial.println("Ethernet LocalIP:");
  Serial.println(Ethernet.localIP());
  
  client.setBufferSize(BUFFER_SIZE);
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  irsend1.begin();
  irsend2.begin();

}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
//
//  unsigned long now = millis();
//  if (now - lastMsg > 2000) {
//    lastMsg = now;
//    ++value;
//    snprintf (msg, MSG_BUFFER_SIZE, "hello world #%ld", value);
//    Serial.print("Publish message: ");
//    Serial.println(msg);
//    client.publish("outTopic", msg);
//  }
}
